package org.learn.java.mq.producer;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.learn.java.mq.MqContent;
import org.learn.java.mq.localTransactionCheck.MyLocalTransactionChecker;
import org.learn.java.mq.localTransactionExecuter.MyLocalTransactionExecuter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.rocketmq.client.producer.LocalTransactionState;
import com.aliyun.openservices.ons.api.Constants;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.transaction.LocalTransactionExecuter;
import com.aliyun.openservices.ons.api.transaction.TransactionProducer;
import com.aliyun.openservices.ons.api.transaction.TransactionStatus;

public class TransactionProducerTest {
	public static Logger logger = LoggerFactory
			.getLogger(TransactionProducerTest.class);
	public static int messageKey = 0;

	public static void main(String[] args) {
		transactionsend();

	}

	public static void transactionsend() {
		// 配置producer参数
		Properties properties = new Properties();
		properties.put(PropertyKeyConst.ProducerId, "PID_blue_xdj_1");
		properties.put(PropertyKeyConst.AccessKey, MqContent.MQ_AccessKey );
		properties.put(PropertyKeyConst.SecretKey,
				"7JbgLiklyNxmkXQkM0iBKWuyqNvnjU");
		LocalTransactionExecuter localTransactionExecuter = new MyLocalTransactionExecuter();
		// 依据参数创建producer
		TransactionProducer transactionProducer = ONSFactory
				.createTransactionProducer(properties,
						new MyLocalTransactionChecker());
		// 启动producer
		transactionProducer.start();
		// 组装消息
		String messageBody = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:sss")
				.format(new Date());
		Message message = new Message("blue_xdj", "test3",
				messageBody.getBytes());
		// 设置消息唯一字段
		message.setKey(messageBody);
		// 事务消息发送
		SendResult sendResult = transactionProducer.send(message,
				localTransactionExecuter, null);
		logger.debug("----messageId:" + sendResult.getMessageId() + "----");
		// demo example 防止进程退出(实际使用不需要这样)
        try {
			TimeUnit.MILLISECONDS.sleep(Integer.MAX_VALUE);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		transactionProducer.shutdown();
	}

}
